package com.leo.stopwatch;
/*Copyright (c) 2010-2012, Daniel Bostwick

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
3. Neither the name of Daniel Bostwick nor the names
   of its contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.*/


import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class StopwatchActivity extends ListActivity {
	

	
	private static String TAG = "StopwatchActivity";
	private static final int menu1=0;
	private static final int menu2=1;
	private static final int menu3=2;
	// View elements in stopwatch.xml
	private TextView m_elapsedTime;
	private Button m_start;
	private Button m_pause;
	private Button m_reset;
	private Button m_lap;
	private ArrayAdapter<String> m_lapList;
	private int count=0;
	// Timer to update the elapsedTime display
    private final long mFrequency = 100;    // milliseconds
    private final int TICK_WHAT = 2; 
	private Handler mHandler = new Handler() {
        public void handleMessage(Message m) {
        	updateElapsedTime();
        	sendMessageDelayed(Message.obtain(this, TICK_WHAT), mFrequency);
        }
    };

    // Connection to the backgorund StopwatchService
	private StopwatchService m_stopwatchService;
	private ServiceConnection m_stopwatchServiceConn = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			m_stopwatchService = ((StopwatchService.LocalBinder)service).getService();
			showCorrectButtons();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			m_stopwatchService = null;
		}
	};
	
	private void bindStopwatchService() {
        bindService(new Intent(this, StopwatchService.class), 
        			m_stopwatchServiceConn, Context.BIND_AUTO_CREATE);
	}
	
	private void unbindStopwatchService() {
		if ( m_stopwatchService != null ) {
			unbindService(m_stopwatchServiceConn);
		}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.stopwatch);
        setListAdapter(new ArrayAdapter<String>(this, R.layout.laps_row));
        
        AdView adView=new AdView(this,AdSize.BANNER, "Publisher ID");
        LinearLayout layout = (LinearLayout)findViewById(R.id.AdLayout);
        layout.addView(adView);
        adView.loadAd(new AdRequest());
        
        startService(new Intent(this, StopwatchService.class));
        bindStopwatchService();

        m_elapsedTime = (TextView)findViewById(R.id.ElapsedTime);
        
        m_start = (Button)findViewById(R.id.StartButton);
        m_pause = (Button)findViewById(R.id.PauseButton);
        m_reset = (Button)findViewById(R.id.ResetButton);
        m_lap = (Button)findViewById(R.id.LapButton);
        
        m_lapList = (ArrayAdapter<String>)getListAdapter();

        mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), mFrequency);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindStopwatchService();
    }
    /*judge button stats start*/
    private void showCorrectButtons() {
    	Log.d(TAG, "showCorrectButtons");
    	
    	if ( m_stopwatchService != null ) {
    		if ( m_stopwatchService.isStopwatchRunning() ) {
    			showPauseLapButtons();
    		} else {
    			showStartResetButtons();
    		}
    	}
    }
    
    private void showPauseLapButtons() {
    	Log.d(TAG, "showPauseLapButtons");
    	
    	m_start.setVisibility(View.GONE);
    	m_reset.setVisibility(View.GONE);
    	m_pause.setVisibility(View.VISIBLE);
    	m_lap.setVisibility(View.VISIBLE);
    }
    
    private void showStartResetButtons() {
    	Log.d(TAG, "showStartResetButtons");

    	m_start.setVisibility(View.VISIBLE);
    	m_reset.setVisibility(View.VISIBLE);
    	m_pause.setVisibility(View.GONE);
    	m_lap.setVisibility(View.GONE);
    }
    
    public void onStartClicked(View v) {
    	Log.d(TAG, "start button clicked");
    	m_stopwatchService.start();
    	
    	showPauseLapButtons();
    }
    
    public void onPauseClicked(View v) {
    	Log.d(TAG, "pause button clicked");
    	m_stopwatchService.pause();
    	
    	showStartResetButtons();
    }
    
    public void onResetClicked(View v) {
    	Log.d(TAG, "reset button clicked");
    	m_stopwatchService.reset();
    	count=0;
    	m_lapList.clear();
    }
    /*judge button stats end*/
    public void onLapClicked(View v) {
    	Log.d(TAG, "lap button clicked");
    	m_stopwatchService.lap();
    	count=count+1;
    	m_lapList.insert(count+"       "+m_stopwatchService.getFormattedElapsedTime(), 0);
    }
    /*count show start*/
    public void updateElapsedTime() {
    	if ( m_stopwatchService != null )
    		m_elapsedTime.setText(m_stopwatchService.getFormattedElapsedTime());
    } @Override
	   
    public boolean onCreateOptionsMenu(Menu menu){
    	super.onCreateOptionsMenu(menu);
    	menu.add(0,menu1,0,(R.string.about)).setIcon(R.drawable.info);
    	menu.add(0,menu2,0,(R.string.exit)).setIcon(R.drawable.exit);menu.add(0, menu3, 0, (R.string.app)).setIcon(R.drawable.app);
    	return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
     switch(item.getItemId())
     {
     case menu1:
    	 showAlertDialog("CEO/作者:Leo\nComments/評論:pcschoolleo@gmail.com\nIcons/圖示:www.iconfinder.com\n"+"original source:https://github.com/bostwick/android-stopwatch\n"+
"original copyright:Daniel Bostwick");
    	 return true;
     case menu2:
    	 finish();
    	 return true;     case menu3:
				Intent intenta = new Intent(Intent.ACTION_VIEW);
				intenta.setData(Uri.parse("market://search?q=pcschoolleo"));
				startActivity(intenta);
				return true;
     }
     return false;
    }
    private void showAlertDialog(String message){
    	new AlertDialog.Builder(this)
    	.setMessage(message)
    	.setPositiveButton("ok",null)
    	.show();
    }
    

    
}